package com.learncloud.security.extension.mobile;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AccountStatusException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author lbx
 * @version 1.0.0
 * @description 手机验证码授权者
 * @date 2021/10/29 12:24
 **/
public class SmsCodeTokenGranter extends AbstractTokenGranter {

    private static final String GRANT_TYPE = "sms_code";
    private final AuthenticationManager authenticationManager;

    public SmsCodeTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService,
                               OAuth2RequestFactory requestFactory, AuthenticationManager authenticationManager) {
        super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
        this.authenticationManager = authenticationManager;
    }


    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {

        Map<String, String> parameters = new LinkedHashMap(tokenRequest.getRequestParameters());
        // 手机号
        String mobile = parameters.get("mobile");
        // 短信验证码
        String code = parameters.get("code");
        // 去掉code
        parameters.remove("code");
        Authentication authentication = new SmsCodeAuthenticationToken(mobile, code);
        ((AbstractAuthenticationToken) authentication).setDetails(parameters);
        try {
            authentication = this.authenticationManager.authenticate(authentication);
        } catch (AccountStatusException e) {
            throw new InvalidGrantException(e.getMessage());
        } catch (BadCredentialsException e) {
            throw new InvalidGrantException(e.getMessage());
        }
        if (authentication != null && authentication.isAuthenticated()) {
            OAuth2Request auth2Request = this.getRequestFactory().createOAuth2Request(client, tokenRequest);
            return new OAuth2Authentication(auth2Request, authentication);
        } else {
            throw new InvalidGrantException("Could not authenticate user:" + mobile);
        }

    }
}
